<?php

class CsvExport extends ECSVExport {
	
	protected function _writeData() {
		// ECSVExport set file pointer to php://temp
		$this->_filePointer = fopen('php://output', 'w');
		parent::_writeData();
		$this->_filePointer = fopen("php://temp", 'w');
	}
	
    public function _writeRow($row) {
        parent::_writeRow($row);
		
		ob_flush();
		flush();
    }
	
	public function download($fileName, $headers=array(), $terminate=true) {
		header('Pragma: public');
		header('Expires: 0');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Content-type: text/csv');
		header("Content-Disposition: attachment; filename=\"$fileName\"");
		header('Content-Transfer-Encoding: binary');
		
		if ($headers) {
			$this->includeColumnHeaders = false;
			$handle = $this->_filePointer = fopen('php://output', 'w');
			fputcsv($handle, $headers, $this->_delimiter, $this->_enclosure);
			fclose($handle);
			ob_flush();
			flush();
		}
		
		$this->toCsv();
		
		if ($terminate) Yii::app()->end();
	}
}
